<?php
class excel{
	/**
	 * 错误信息
	 * @method checkFilesError
	 * @param  [string] $files   [description]
	 * @author NewFuture
	 */
	public static function checkFilesError($files)
	{    
		$checkFile = new stdClass();
    	$checkFile->value=true;
    	$checkFile->result='';
    	$error='';
		if($files!="undefined" && !empty($files['error'])){
			switch($files['error']){
				case '1':
					$error = '导入的文件超过了 php.ini 中 upload_max_filesize 选项限制的值！';
					break;
				case '2':
					$error = '导入文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值！';
					break;
				case '3':
					$error = '导入文件只有部分被导入！';
					break;
				case '4':
					$error = ' 没有文件被导入！';
					break;
				case '6':
					$error = ' 找不到临时文件夹！';
					break;
				case '7':
					$error = ' 文件导入失败';
					break;
				default:
					$error = '未知错误！';
					break;
			}
			//检查临时目录
		}else if(empty($files['tmp_name']) || $files['tmp_name'] == 'none'){
			$error = ' 没有文件被导入！';
		}
		if(!empty($error)){
			$checkFile->result = $error;
			$checkFile->value = false;
		}
		return $checkFile;
	}
	/**
	 * 检查保存文件的目录是否存在
	 * @method checkSaveDir
	 * @param  [string] $files   [description]
	 * @author NewFuture
	 */
	public static function createSaveDir($dir,$auth)
	{ 
        $checkDir = new stdClass();
    	$checkDir->value=true;
		if(!file_exists($dir)){
			$createResult = mkdir($dir,$auth,true);
			$checkDir->value = !$createResult?false:true;
			$checkDir->result=!$createResult?"目录创建失败":"";
		}else{
			chmod($dir,$auth); 
			$checkDir->result="";
		}
    	return $checkDir;
	}
	//获取文件类型
    public static function getExt($files)
    {
        $extStr = explode('.', $files);
        $count = count($extStr)-1;
        return $extStr[$count];
    }
    public static function resourceDir(){
		return Yaf_Application::app()->getConfig()->resource->dir;
	}
	function importExcel($fileObj,$auth,$params){
		$checkFile = self::checkFilesError($fileObj);
		if(!$checkFile)
			return $checkFile->result;
		$fileType = self::getExt($fileObj['name']);
		if(strtolower($fileType) != "xlsx"&&strtolower($fileType) != "xls")
			return '不是Excel文件,请重新导入';
		/*$saveDir = self::createSaveDir($dir,$auth);
		if(!$saveDir)
			return $saveDir->result;*/
		$filePath = self::resourceDir().$fileObj['name'];
		if(!move_uploaded_file($fileObj['tmp_name'],$filePath))
			return 'Excel文件导入失败';
		return self::getData($filePath,$params,strtolower($fileType));
	}
	//获取数据
	function getData($filePath,$params,$fileType){
		$list =array();
		$count = count($params);
		$objReader=null;
		if($fileType=="xlsx"|| $fileType=="xls"){
			date_default_timezone_set('Asia/shanghai');
			$objReader=PHPExcel_IOFactory::createReader('Excel2007');
		}else{
			$objReader=PHPExcel_IOFactory::createReader('Excel5');
		}
		$objPHPExcel=$objReader->load($filePath);
		$sheet=$objPHPExcel->getSheet(0);//获取第一个工作表
		$highestRow=$sheet->getHighestRow();//取得总行数
		$highestColumn=$sheet->getHighestColumn(); //取得总列数
		for($j=2;$j<=$highestRow;$j++){//行
			$f=0;
			$car = new stdClass();
			for($k='A';$k<=$highestColumn;$k++){//列
				$car->$params[$f] = trim($objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue());
				$f++;
			}
        	array_push($list,$car);
		}
		return $list;
	}
	//导出数据
	function exportData($paramTop,$param){
		//excel表格索引字母
		$letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
		date_default_timezone_set('Asia/shanghai');
		$objExcel = new PHPExcel();
		$objExcel->setActiveSheetIndex(0);
		$objActsheet = $objExcel->getActiveSheet();
			$i = 0;
			foreach($paramTop as $key => $value){
				$objActsheet->setCellValue($letter[$i].'1',$value);
				$i++;
			}
		$baseRow = 2;		
		foreach($param as $r=>$dataRow){
			$row = $baseRow + $r;
			//动态生成表格数据的方法，但是接收的数组值需要和表格信息对应
			$j = 0;
			foreach($dataRow as $value){
				$objActsheet->setCellValue($letter[$j].$row,chunk_split($value,15));
				$j++;
			}
			// $objActsheet->setCellValue('A'.$row,$dataRow->type);
			// $objActsheet->setCellValue('B'.$row,$dataRow->vin);
			// $objActsheet->setCellValue('C'.$row,$dataRow->ein);
			// $objActsheet->setCellValue('D'.$row,$dataRow->color);
			// $objActsheet->setCellValue('E'.$row,$dataRow->hubNum);
			// $objActsheet->setCellValue('F'.$row,$dataRow->fuelType);
			// $objActsheet->setCellValue('G'.$row,$dataRow->dpm);
			// $objActsheet->setCellValue('H'.$row,$dataRow->seatNum);
		}
		
		//设置单元格的水平对齐方式
		$objExcel->getActiveSheet()->getStyle('A1:'.$letter[count($paramTop)].'1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
		//设置excel名称
		$objExcel->getActiveSheet()->setTitle('carInfo');
		//将生成的excel下载
		@header('Content-Type: application/vnd.ms-excel');
		//header("Content-type: application/octet-stream");
		header('Content-Disposition: attachment;filename="carInfo.xls"');
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1');
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0

		$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
		$objWriter->save('php://output');		
	}
}
?>